package cn.sw.file.config.monitor;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;

/**
 * @Description: 数据库连接检查器
 * @Author: 张众森
 * @Date: 2025/5/10
 */
@Component
public class DatabaseConnectionChecker implements CommandLineRunner {

    @Autowired
    private DataSource dataSource;

    @Override
    public void run(String... args) {
        try (Connection connection = dataSource.getConnection()) {
            if (connection != null && !connection.isClosed()) {
                String url = connection.getMetaData().getURL();
                String username = connection.getMetaData().getUserName();
                String driverName = connection.getMetaData().getDriverName();

                System.out.println("\n--------------- 数据库连接成功 ---------------\n");
                System.out.println("\n数据库地址: " + url+"\n");
                System.out.println("\n用户名: " + username+"\n");
                System.out.println("\n驱动名称: " + driverName+"\n");
                System.out.println("\n----------------------------------------------\n");
            }
        } catch (SQLException e) {
            System.err.println("数据库连接失败！");
            e.printStackTrace();
        }
    }
}
